import random,time,requests,json

# from db import db
from model.models import db
from flask import Blueprint, request, jsonify, send_file, redirect
from flask_restful import Api, Resource,reqparse
from captcha.image import ImageCaptcha
from utils.myredis import r
from utils.sms import send_message
from utils.myjwt import myjwt
from model.models import *

user_dp = Blueprint('user_dp', __name__)

api = Api(user_dp)

class ImgCode(Resource):
    def get(self,uuid):
        if not uuid:
            return jsonify({"code":400,"msg":"没有参数"})
        #生成图片验证码
        code = random.randint(1000,9999)
        img = ImageCaptcha()
        img_byte = img.generate(str(code))
        #存到redis
        key = "code_%s" % uuid
        r.set_str(key,code,time=300)
        return send_file(img_byte,"png")

api.add_resource(ImgCode,"/imgcode/<uuid>")


class SmsCode(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("mobile")
        req.add_argument("imagecode")
        req.add_argument("uuid")
        args = req.parse_args()
        mobile = args["mobile"]
        imagecode = args["imagecode"]
        uuid = args["uuid"]
        if not mobile:
            return jsonify({"code":400,"msg":"参数没有"})
        key = "code_%s" % uuid
        code = r.get_str(key)
        if not code:
            return jsonify({"code":400,"msg":"图片验证码以过期"})
        print(code,imagecode)
        if code != imagecode:
            return jsonify({"code":400,"msg":"图片验证码错误"})

        code = random.randint(1000,9999)
        send_message(mobile,code)
        key = "sms_%s" % mobile
        r.set_str(key,code,60)
        return jsonify({"code":200,"msg":"获取成功"})

api.add_resource(SmsCode,"/sendsms")


class Login(Resource):
    def post(self):
        data = reqparse.RequestParser()
        data.add_argument("mobile")
        data.add_argument("code")
        args = data.parse_args()
        mobile = args["mobile"]
        code = args["code"]
        if not all([mobile,code]):
            return jsonify({"code":400,"msg":"参数没有"})
        #校验验证码
        key = "sms_%s" % mobile
        recode = r.get_str(key)
        print(">>",recode)
        if not recode:
            return jsonify({"code":400,"msg":"验证码过期"})
        if code != recode:
            return jsonify({"code":400,"msg":"验证码错误"})
        user_info = User.query.filter(User.mobile == mobile).first()
        if user_info:
            #用户存在直接登录
            data = {"data":{"userid":user_info.id,"mobile":user_info.mobile,"exptime":int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code":200,"msg":"登录成功","token":token,"userid":user_info.id})
        if not user_info:
            #没有用户进行注册
            user = User(mobile=mobile)
            db.session.add(user)
            db.session.commit()
            data = {"data":{"userid":user_info.id,"mobile":user_info.mobile,"exptime":int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code":200,"msg":"注册成功并登录","token":token,"userid":user_info.id})

api.add_resource(Login,"/login")


# 微博登录
class WeiBoUserHeadler(Resource):
    def get(self):
        client_id = "3674019597"
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (client_id, redirect_uri)
        return jsonify({"code":200,"url":url})

api.add_resource(WeiBoUserHeadler,"/getWBurl")


class WeiBoHeadler(Resource):
    def get(self):
        code = request.args.get("code")
        data = {"client_id": '3674019597',
                "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res1 = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        mes = json.loads(res1.text)
        # 获取微博平台的用户信息
        uid = mes["uid"]
        token = mes["access_token"]
        # 查询此id是否存在
        sql = "select user.id from sf_login inner join user on user.id=sf_login.userid where sf_login.uid='%s'"%(uid)
        user = db.session.execute(sql)
        if user:
            for i in user:
                # 生成token，跳转到vue中转页
                token = myjwt.jwt_encode(data={"data":{"uid":i[0],"exp":int(time.time())}})
                return redirect("http://localhost:8080/#/updatetoken?token="+token+"&userid="+str(i[0]))
        return redirect("http://localhost:8080/#/wbdl?uid="+str(uid)+"&token="+str(token))

    def post(self):
        # 接收参数
        data = json.loads(request.data)
        mobile = data["mobile"]
        uid = data["uid"]
        token = data["token"]
        # 加入用户表
        user = User.query.filter(User.mobile == mobile).first()
        if not user:
            # 添加
            u = User(mobile=mobile, nikename=mobile)
            db.session.add(u)
            db.session.commit()
            # 获取用户信息
            user = User.query.filter(User.mobile == mobile).first()
        sfuser = SfLogin(userid=user.id, webfrom="wb", uid=uid, token=token)
        print("sss", sfuser)
        db.session.add(sfuser)
        db.session.commit()
        data = {"data": user.id, "exp": int(time.time())}
        token = myjwt.jwt_encode(data)
        return redirect("http://localhost:8080/#/updatetoken?token=" + token + "&userid=" + str(user.id))

api.add_resource(WeiBoHeadler,"/user/weiboCallback/")
